package com.ifmvo.togetherad.core.life

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import com.ifmvo.togetherad.core.helper.BaseHelper
import com.xinyue.sdk.utilcode.util.ActivityUtils
import java.lang.ref.WeakReference

/**
 * @author liu hong liang
 * @date 2021/3/15
 * 主要用于管理activity的生命周期，方便对
 *
 */

object ActivityLifeManager {
    val requireDestroyAdsList = mutableListOf<ActivityAdsHolder>()
    fun init(app: Application) {
        app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
            override fun onActivityPaused(activity: Activity?) {

            }

            override fun onActivityResumed(activity: Activity?) {

            }

            override fun onActivityStarted(activity: Activity?) {

            }

            override fun onActivityDestroyed(activity: Activity?) {
                // 对需要根据activity生命周期调用onDestroy的广告进行调用
                val it = requireDestroyAdsList.iterator()
                while (it.hasNext()) {
                    val holder = it.next()
                    if (holder.baseHelperWr.get() == null || holder.activityWr.get() == null || holder.remove) {
                        it.remove()
                    } else if (holder.activityWr.get() == activity) {
                        holder.baseHelperWr.get()?.destroy()
                        it.remove()
                    }
                }
            }

            override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {

            }

            override fun onActivityStopped(activity: Activity?) {

            }

            override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {

            }
        })
    }

    fun getActivity(context: Context?): Activity? {
        return if (context != null && context is Activity) {
            context
        } else {
            ActivityUtils.getTopActivity()
        }
    }

    data class ActivityAdsHolder(
        val activityWr: WeakReference<Activity>,
        val baseHelperWr: WeakReference<BaseHelper>,
        var remove: Boolean = false
    )
}